package cn.elwy.kit.file.service;

import java.io.File;

import cn.elwy.common.util.io.FileUtil;

public class FileRename {

  public boolean rename(String filePath, String prefix, String replacePrefix, String postfix, String replacePostfix) {
    return rename(new File(filePath), prefix, replacePrefix, postfix, replacePostfix);
  }

  public boolean rename(File file, String prefix, String replacePrefix, String postfix, String replacePostfix) {
    if (replacePrefix == null) {
      replacePrefix = "";
    }
    if (replacePostfix == null) {
      replacePostfix = "";
    }
    if (file.isDirectory()) {
      File[] listFiles = file.listFiles();
      for (File chield : listFiles) {
        rename(chield, prefix, replacePrefix, postfix, replacePostfix);
      }
      String sortName = file.getName();
      sortName = sortName.replace("^" + prefix, replacePrefix);
      sortName = sortName.replace(postfix + "$", replacePostfix);
      File destFile = new File(file.getParentFile(), sortName);
      return file.renameTo(destFile);
    } else {
      String ext = FileUtil.getExtName(file.getName());
      String sortName = FileUtil.getShortFileName(file);
      sortName = sortName.replace(prefix, replacePrefix);
      sortName = sortName.replace(postfix, replacePostfix);
      File destFile = new File(file.getParentFile(), sortName + "." + ext);
      return file.renameTo(destFile);
    }
  }

}
